module Rpbk
  class Set
    attr_accessor :groups, :controllers, :name
    def initialize
      @holder = Holder.new
      @data = {}
    end
    
    def find key, controller_name = '', action_name = ''
      ret = @holder.find_attr(key)
      if controller = @holder.find_controller(controller_name)
        ret = controller.find_attr(key) || ret
      end
      if action = @holder.find_action(controller_name, action_name)
        ret = action.find_attr(key) || ret
      end
      ret
    end
    
    def find_layout controller_name = '', action_name = ''
      ret = @holder.layout
      if controller = @holder.find_controller(controller_name)
        ret = controller.layout || ret
      end
      if action = @holder.find_action(controller_name, action_name)
        ret = action.layout || ret
      end
      ret
    end
    
    def find_in_group key, group_name
      if group = @holder.find_group(group_name)
        return group.find_attr(key)
      end
      nil
    end
    
    def config(&block)
      instance_exec(&block)
      nil
    end
    
    def set attributes
      attributes.kind_of? Hash and attributes.each do |key, value|
        @holder.add_attr Attribute.new(key, value)
      end
    end
    
    def group name, options = {}, &block
      process_group :group, name, options, &block
    end
    
    def controller name, options = {}, &block
      process_group :controller, name, options, &block
    end
    
    def action name, options ={}, &block
      process_group :action, name, options, &block
    end
    
    def layout name
      @holder.set_layout name.to_sym
    end
    
    private
    
      def process_group type, name, options, &block
        @holder.set_scope type, name.to_sym
        @holder.extend_from(options[:extend]) if options[:extend]
        yield if block_given?
        @holder.drop_last_scope
      end
  end

  class ActionControllerNotSpecifiedException < Exception
  end 
end